import Component, {
    get,
    post,
    forceLogin
} from '../ZES';

export default class Material extends Component {
    @get async get(cx) {
        let _id = cx.param('_id');
        cx.assert.notNull(_id);
        return await cx.model.Material.findById(_id);
    }

    @post(null, forceLogin)
    @get(null, forceLogin)
    async save(cx) {
        let obj = cx.params();
        if (typeof obj.content === 'string') {
            obj.content = JSON.parse(obj.content);
        }
        if (obj._id) {
            return await cx.model.Material.findOneAndUpdate({
                _id: obj._id,
                author: cx.state.user._id
            }, obj);
        } else {
            obj.author = cx.state.user._id;
            return await cx.model.Material.insert(obj);
        }
    }
}
